package com.normal.zbase.impl.tools.utils

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import java.lang.ref.WeakReference

/**
 * 三疯
 * *************************
 * 监听生命周期
 * *************************
 */
class LifecycleBindOwner {
    private lateinit var mLifecycleOwner: WeakReference<LifecycleOwner>

    companion object {
        fun instance(): LifecycleBindOwner {
            return LifecycleBindOwner()
        }
    }

    /**
     * 绑定Activity/Fragment生命周期
     * LifecycleBindOwner.instance().bindView(lifecycleOwner) { source, event ->}
     */
    fun bindView(lifecycleOwner: LifecycleOwner, lifecycleEventObserver: LifecycleEventObserver) {
        mLifecycleOwner = WeakReference<LifecycleOwner>(lifecycleOwner)
        mLifecycleOwner.get()?.lifecycle?.addObserver(lifecycleEventObserver)
    }

    /**
     * 绑定App生命周期
     */
    fun bindApp(defaultLifecycleObserver: DefaultLifecycleObserver) {
        ProcessLifecycleOwner.get().lifecycle.addObserver(defaultLifecycleObserver)
    }

}